import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { SorterResult } from 'antd/es/table/interface';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { Button, Divider, message, Modal } from 'antd';
import { get } from 'lodash';

import { queryRule, removeRule } from './service';
import AttrModal from './components/AttrModal';

const { confirm } = Modal;

interface goods {
  goods_skus: Array<any>;
  id: number | null;
}

const initGoods = {
  goods_skus: [],
  id: null,
};

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [goods, setGoods] = useState<goods>(initGoods);
  const actionRef = useRef<ActionType>();


  const showDeleteConfirm = (id: string) => {
    confirm({
      title: '确认删除?',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        const { code } = await removeRule(id);
        if(code === 0) {
          message.success('删除成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      },
      onCancel() {
      },
    });
  }

  const columns: ProColumns<any>[] = [
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '图片',
      dataIndex: 'main_pic',
      hideInSearch: true,
      render: (val) => val && <img alt="商品图片" src={val} style={{ width: 50, height: 50 }} />,
    },
    // {
    //   title: '是否上架',
    //   dataIndex: 'online',
    //   hideInSearch: true,
    //   render: (v) => (v === 1 ? '是' : '否'),
    // },
    {
      title: '分类',
      dataIndex: 'category.name',
      hideInSearch: true,
      render: (v, record) => get(record, ['category', 'name'], '-'),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          {/* <a
            onClick={() => {
              setGoods(record);
            }}
          >
            商品规格
          </a>
          <Divider type="vertical" /> */}
          <a
            onClick={() => {
              history.push({
                pathname: `/goods/create/${record.id}`,
              });
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a type="text" onClick={() => showDeleteConfirm(record.id)}>
            删除
          </a>
        </>
      ),
    },
  ];

  const attrProps = {
    goods_skus: goods.goods_skus,
    visible: true,
    onCancel: () => setGoods(initGoods),
  };

  return (
    <PageHeaderWrapper>
      <ProTable<any>
        headerTitle="商品列表"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<any>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{}}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              history.push({
                pathname: '/goods/create',
              });
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          const ans = {
            ...params,
            page: params?.current,
          };
          delete ans?.current;
          delete ans?._timestamp;
          const { data } = await queryRule(ans);
          data.data = data.list;
          return data;
        }}
        columns={columns}
        rowSelection={{}}
      />
      {goods.id && <AttrModal {...attrProps} />}
    </PageHeaderWrapper>
  );
};

export default TableList;
